import { readFileSync } from 'fs';
import * as vscode from 'vscode';

let curWebViewPannel: vscode.WebviewPanel | null = null;
const resourceRootPath = 'src/webview/a'

function createWebViewPannel(resourceRootUri: vscode.Uri) {
  return vscode.window.createWebviewPanel(
    'catCoding',
    'Cat Coding',

    vscode.ViewColumn.One,// 打开的位置
    {
      enableScripts: true,
      localResourceRoots: [resourceRootUri]
    }
  );

}

function replaceHtmlUri(htmlContent: string, resourceRootUri: vscode.Uri) {
  return htmlContent.replace(
    /(src|href)="\.\/([^"]*)"/g,
    (_, attr, resourcePath) => {
      const resourceUri = curWebViewPannel!.webview.asWebviewUri(vscode.Uri.joinPath(resourceRootUri, resourcePath));
      return `${attr}="${resourceUri}"`;
    }
  )
}
export function setupTestWebViewCommand(context: vscode.ExtensionContext) {
  const resourceRootUri = vscode.Uri.joinPath(context.extensionUri, resourceRootPath)
  if (!curWebViewPannel) {
    curWebViewPannel = createWebViewPannel(resourceRootUri);
  }


  const htmlContent = readFileSync(vscode.Uri.joinPath(resourceRootUri, 'index.html').fsPath, 'utf8')
  curWebViewPannel.webview.html = replaceHtmlUri(htmlContent, resourceRootUri)

  curWebViewPannel.webview.onDidReceiveMessage

}


